package com.hzsoft.sys.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.hzsoft.base.entity.BJuiJSON;
import com.hzsoft.base.entity.Page;
import com.hzsoft.sys.entity.SysMenu;
import com.hzsoft.sys.entity.SysRole;
import com.hzsoft.sys.entity.SysRoleMenu;
import com.hzsoft.sys.entity.SysUser;
import com.hzsoft.sys.entity.SysUserRole;
import com.hzsoft.sys.service.SysRoleService;
import com.hzsoft.sys.service.SysUserRoleService;
import com.hzsoft.sys.service.SysUserService;
import com.hzsoft.util.Ch2Pinyin;
import com.hzsoft.util.Const;
import com.hzsoft.util.DateUtil;
import com.hzsoft.util.StrUtil;
import com.hzsoft.util.StringUtil;
import com.hzsoft.util.SystemUtil;

@Controller
@RequestMapping("/system/user")
public class SysUserController {
	@Autowired
	private SysUserService userService;
	@Autowired
	private SysUserRoleService userRoleService;
	@Autowired
	private SysRoleService roleService;
	@Autowired
	private TransactionDefinition txDefinition;
	@Autowired
	private PlatformTransactionManager txManager;
	/*
	 * @RequestMapping("/showUser/{id}") public String showUser(@PathVariable
	 * String userId,HttpServletRequest request) {
	 * 
	 * SysUser u = userService.selectByPrimaryKey(userId);
	 * 
	 * request.setAttribute("user", u);
	 * 
	 * return "showUser"; }
	 */

	@RequestMapping("/systemUserList")
	public ModelAndView showUser(@ModelAttribute SysUser user, Model model,
			HttpServletRequest request, HttpServletResponse response) {

		// 分页设置
		String pageCurrent = request.getParameter("pageCurrent");
		Page page = new Page();
		if (StringUtils.isNotBlank(pageCurrent)) {
			page.setPageCurrent(Integer.parseInt(pageCurrent));
			user.setPage(page);
		}
		if (user.getName() == null) {
			user.setName("");
		}
		user.setName(user.getName().trim());
		List<SysUser> list = userService.listPageUser(user);

		model.addAttribute("user", user);
		model.addAttribute("page", user.getPage());
		model.addAttribute("list", list);

		return new ModelAndView("/system/user/userList");

	}

	/**
	 * 弹出添加页面
	 * 
	 * @param response
	 * @param request
	 * @return
	 */
	@RequestMapping("/toAddUser")
	public ModelAndView toAddUser(@ModelAttribute SysUser user,
			HttpServletResponse response, HttpServletRequest request) {
		ModelAndView model = new ModelAndView();

		model.setViewName("system/user/addUser");
		return model;
	}

	/**
	 * 功能设置：添加
	 */
	@RequestMapping(value = "/addUser")
	public ModelAndView addUser(SysUser user, HttpServletRequest request,
			HttpServletResponse response) {
		ModelAndView mv = new ModelAndView();
		BJuiJSON bjui = new BJuiJSON();
		SysUser list = userService.selectByPrimaryKey(user.getUserId());

		String salt = StringUtil.randomString(4);
		user.setSalt(salt);
		String sk = Ch2Pinyin.getPinYinHeadChar(user.getUserName().trim());// 助记码，同时也是登录名
		String pw = SystemUtil.getMD5Code("123456" + salt);// 默认密码
		String ip = SystemUtil.getIpAddress(request);
		user.setSk(sk);
		user.setRegIp(ip);
		user.setRegTime(DateUtil.str2Date(DateUtil.getCurrentDateAndTime()));// 当前日期
		user.setName(sk);
		user.setPassword(pw);

		if (list != null) {
			bjui.setStatusCode("300");
			bjui.setMessage("该用户已经存在，请重新输入用户编码！");
		} else {
			try {
				userService.insertSelective(user);

				bjui.setStatusCode("200");
				bjui.setMessage("添加成功！！！");
				bjui.setTabid("navtab-user");
				bjui.setCloseCurrent(true);

			} catch (Exception e) {
				e.printStackTrace();
				bjui.setStatusCode("300");
				bjui.setMessage("添加失败！！！");
			}
		}
		String msg = JSONObject.fromObject(bjui).toString();
		mv.addObject("msg", msg);
		mv.setViewName("msg");
		return mv;
	}

	/**
	 * 功能设置：删除
	 */
	@RequestMapping(value = "/deleteUser")
	public ModelAndView deleteUser(@ModelAttribute SysUser user,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		BJuiJSON bjui = new BJuiJSON();
		ModelAndView mv = new ModelAndView();

		try {
			// menuService.deleteAll(user);

			userService.deleteByPrimaryKey(user.getUserId());

			bjui.setStatusCode("200");
			bjui.setMessage("删除成功！！！");
			bjui.setTabid("navtab-user");
		} catch (Exception e) {
			e.printStackTrace();
			bjui.setStatusCode("300");
			bjui.setMessage("删除失败！！！");
		}

		String msg = JSONObject.fromObject(bjui).toString();
		mv.addObject("msg", msg);
		mv.setViewName("msg");
		return mv;
	}

	/**
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/toUpdateUser")
	public ModelAndView toUpdateUser(SysUser user) {
		ModelAndView mv = new ModelAndView();
		System.out.println("-----------"+user.getUserId());
		mv.addObject("user", userService.selectByPrimaryKey(user.getUserId()));
		// mv.addObject("menu", menuService.selectMenu(menu.getpMenuid()));
		mv.setViewName("system/user/updateUser");
		return mv;
	}

	/**
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/updateUser", method = RequestMethod.POST)
	public ModelAndView updateUser(SysUser user, HttpServletRequest request,
			HttpServletResponse response) {
		ModelAndView mv = new ModelAndView();
		BJuiJSON bjui = new BJuiJSON();

		try {
			userService.updateByPrimaryKeySelective(user);

			bjui.setStatusCode("200");
			bjui.setMessage("更新成功！！！");
			bjui.setTabid("navtab-user");
			bjui.setCloseCurrent(true);

		} catch (Exception e) {
			bjui.setStatusCode("300");
			bjui.setMessage("更新失败！！！");
		}
		String msg = JSONObject.fromObject(bjui).toString();
		mv.addObject("msg", msg);
		mv.setViewName("msg");
		return mv;
	}
	
	/**
	 * 设置岗位
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/toSetRole")
	public ModelAndView toSetRole(@ModelAttribute SysRole result,String userId,HttpServletResponse response, HttpServletRequest reques) {
		ModelAndView mv = new ModelAndView();
		//获取所有岗位
		List<SysRole> roleList = roleService.selectAll();
		//获取当前用户的岗位 select * from sys_user_role where user_id='0001'
		List<SysUserRole> userRoleList = userRoleService.selectByUserId(userId);
			
		for(SysRole role:roleList){
			for(SysUserRole ur:userRoleList){
				if(role.getRoleId().equals(ur.getRoleId())){
					role.setChecked("checked");
				}
			}
		}
		
		mv.addObject("roleList", roleList);
		mv.addObject("userId", userId);
		mv.setViewName("system/user/setRole");
		return mv;
	}
	
	/**
	 * 设置岗位
	 * 删除原来的岗位sys_user_role,修改sys_user中的岗位
	 * @param user
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/setRole")
	public ModelAndView setRole(SysUser user,SysUserRole record,String roleId,String userId, HttpServletRequest request,
			HttpServletResponse response) {
		TransactionStatus status = txManager.getTransaction(txDefinition);
		ModelAndView mv=new ModelAndView();
		BJuiJSON bjui = new BJuiJSON();
		//一个人员对应一个角色
		user.setUserId(userId);
		user.setRoleId(roleId);//
		record.setUserId(userId);
		
		record.setRoleId(roleId.replaceAll(",",""));

//		String[] a = StrUtil.funNsplit(roleId);
////		record.setRoleIds(StrUtil.funNsplit(roleId));
//		for (String str : a) {
//			record.setRoleId(str);
//		}
		
		try {
			if (StringUtils.isNotBlank(roleId)) {
				userRoleService.deleteByUserId(userId);	//先删除角色的菜单
				userService.updateByPrimaryKeySelective(user);
				userRoleService.insertSelective(record);
				
				bjui.setStatusCode("200");
				bjui.setMessage("设置成功！！！");
				bjui.setTabid("navtab-role");
				bjui.setCloseCurrent(true);
				txManager.commit(status);
			}else{
				bjui.setStatusCode("300");
				bjui.setMessage("必须选一个岗位！");
			}
				
		}catch (Exception e) {
			txManager.rollback(status);
			e.printStackTrace();				
			bjui.setStatusCode("300");
			bjui.setMessage("设置失败！！！");
		}
		
		String msg = JSONObject.fromObject(bjui).toString();
		
		mv.addObject("msg", msg);
		mv.setViewName("/msg");
		return mv;
	}
	

	/**
	 * 跳转到修改密码
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/toChangePw")
	public ModelAndView toChangePw(SysUser user, HttpServletResponse response,HttpServletRequest request) throws IOException{
		ModelAndView mv = new ModelAndView();
		String userId=((SysUser)request.getSession().getAttribute(Const.SESSION_USER)).getUserId();		
		mv.addObject("user", userService.selectByPrimaryKey(userId));
		mv.setViewName("system/user/updatePw");
		return mv;
	}

	/**
	 * 修改密码时 重新生成 salt
	 * @param user
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/updatePw", method = RequestMethod.POST)
	public ModelAndView updatePw(SysUser user, HttpServletRequest request,
			HttpServletResponse response,HttpSession session) {
		ModelAndView mv = new ModelAndView();
		BJuiJSON bjui = new BJuiJSON();
		
		String salt = StringUtil.randomString(4);
		user.setSalt(salt);
		String pw = SystemUtil.getMD5Code(user.getPassword() + salt);// 默认密码
		user.setPassword(pw);

		userService.updateByPrimaryKeySelective(user);
		
		bjui.setStatusCode("200");
//		bjui.setMessage("密码修改成功！");
		bjui.setCloseCurrent(true);
		bjui.setForward("logout.do");
		bjui.setForwardConfirm("密码修改成功！请重新登录");
		String msg = JSONObject.fromObject(bjui).toString();
		mv.addObject("msg", msg);
		mv.setViewName("msg");
		
		session.removeAttribute("menulist");
		session.removeAttribute(Const.SESSION_USER);
		
		return mv;
		
	}

	/**
	 * 密码重置功能
	 * 
	 * @param user
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/resetPw", method = RequestMethod.POST)
	public ModelAndView reset(SysUser user, HttpServletRequest request,
			HttpServletResponse response) {
		ModelAndView mv = new ModelAndView();
		BJuiJSON bjui = new BJuiJSON();
		String salt = StringUtil.randomString(4);
		user.setSalt(salt);
		String pw = SystemUtil.getMD5Code("123456" + salt);// 默认密码
		user.setPassword(pw);

		try {
			userService.updateByPrimaryKeySelective(user);

			bjui.setStatusCode("200");
			bjui.setMessage("密码重置成功！");
			bjui.setTabid("navtab-user");
			bjui.setCloseCurrent(true);

		} catch (Exception e) {
			bjui.setStatusCode("300");
			bjui.setMessage("密码重置失败，请联系管理员！");
		}
		String msg = JSONObject.fromObject(bjui).toString();
		mv.addObject("msg", msg);
		mv.setViewName("msg");
		return mv;
	}

}
